package com.java01.net.service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;

public class TimeClient {

	private final String SERVER_ADDRESS = "localhost";
	private final int SERVER_PORT = 1688;
	private Socket socket;
	private int timeout = 2000;
	
	public TimeClient(){

		BufferedReader in = null;
		
		try {
			InetAddress addr = InetAddress.getByName(SERVER_ADDRESS);
			SocketAddress sockaddr = new InetSocketAddress(addr, SERVER_PORT);
			socket = new Socket();
			socket.connect(sockaddr, timeout);
			
			in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			String response = in.readLine();
			System.out.println(String.format("Server Timestamp = %1$s",response));
			
		}catch (Exception e) {
			System.err.println(String.format("Can not connect to %1$s:%2$d", SERVER_ADDRESS,SERVER_PORT));
		}finally{
			if(in!=null){
				try {
						in.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			
			if(socket!=null){
				try {
					socket.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	public static void main(String[] args) {
		new TimeClient();
	}
}
